package com.tom.architect02.structure.droute;

import android.app.Activity;
import android.content.Intent;

import java.util.HashMap;
import java.util.Map;

/**
 * Added by Tom on 2024/05/31.
 */
public class Router {
    // 通过表，找到对应的clz。ARoute的实现原理

    final Map<String, Map<String, Class<?>>> groupMap = new HashMap<>(); // 分组，分组里面又有class
    // 具体的routeMap，将所有的activity，注册进来，通过字符串能找到Activity。然后通过class进行跳转。
    final Map<String, Class<?>> routeMap = new HashMap<>();


    private Router() {
    }

    public final static class Holder {
        static Router INSTANCE = new Router();
    }

    public static Router getInstance() {
        return Holder.INSTANCE;
    }

    public static void init() {
        // do init 借助注解处理器。

    }


    // 注册操作(组名+具体类)： /main/MainActivity
    public void register(String path, Class<?> clz) {
        String[] strArray = path.split("/");
        if (strArray.length > 2) {
            String groupName = strArray[1];
            String routeName = path;

            Map<String, Class<?>> group = null;
            if (groupMap.containsKey(groupName)) {
                group = groupMap.get(groupName);
            }
            if (group == null) {
                group = new HashMap<>();
                groupMap.put(groupName, group);
            }

            if (group != null) {
                group.put(routeName, clz);
            }
        }
    }

    public void startActivity(Activity activity, String path) {
        String[] strArray = path.split("/");
        if (strArray.length > 2) {
            String groupName = strArray[1];
            String routeName = path;

            Map<String, Class<?>> group = null;
            if (groupMap.containsKey(groupName)) {
                group = groupMap.get(groupName);
            }
            // 在map中找到注册的信息，
            if (group != null && group.containsKey(routeName)) {
                // 有没有routeName这个元素。
                Class<?> clz = group.get(routeName);
                activity.startActivity(new Intent(activity, clz));
            }
        }
    }

}
